package com.hmall.search.web;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.constant.EsConstant;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Vsunks.v
 * @Date 2022/8/10 17:39
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description:
 */
@RestController
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 搜索栏自动补全
     * @param key
     * @return
     */
    @GetMapping("/suggestion")
    public List<String> searchSuggestion(String key){
        SearchRequest request = new SearchRequest(EsConstant.ITEM_INDEX);
        request.source().fetchSource(new String[0], null);
        request.source().suggest(
                new SuggestBuilder()
                .addSuggestion("item_suggestion",
                        new CompletionSuggestionBuilder("suggestion")
                        .prefix(key)
                        .skipDuplicates(true)
                        .size(10)
                )
        );
        List<String> list = new ArrayList<>();
        try {
            SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion suggestion = searchResponse.getSuggest().getSuggestion("item_suggestion");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }


    @PostMapping("/list")
    public PageDTO searchList(@RequestBody RequestParams params){
        SearchRequest request = new SearchRequest(EsConstant.ITEM_INDEX);

        PageDTO pageDTO = new PageDTO<>();
        List<ItemDoc> itemDocs = new ArrayList<>();
        queryCondition(params,request);

        if ("sold".equals(params.getSortBy())){
            request.source().sort(params.getSortBy(), SortOrder.DESC);
        }else if ("price".equals(params.getSortBy())){
            request.source().sort(params.getSortBy(),SortOrder.DESC);
        }

        request.source().from((params.getPage()-1)*params.getSize()).size(params.getSize());
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        try {
            SearchResponse search = client.search(request, RequestOptions.DEFAULT);
            long value = search.getHits().getTotalHits().value;
            pageDTO.setTotal(value);
            SearchHit[] hits = search.getHits().getHits();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (highlightFields != null && highlightFields.size() > 0){
                    HighlightField highlightField = highlightFields.get("name");
                    if (highlightField != null){
                        String name = highlightField.getFragments()[0].toString();
                        itemDoc.setName(name);
                    }
                }
                itemDocs.add(itemDoc);
            }
            pageDTO.setList(itemDocs);
            return pageDTO;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pageDTO;
    }

    /**
     * 过滤项聚合功能
     * @param params
     * @return
     */
    @PostMapping("/filters")
    public Map<String,List<String>> filters(@RequestBody RequestParams params){
        SearchRequest request = new SearchRequest(EsConstant.ITEM_INDEX);

        queryCondition(params,request );
        request.source().size(0);

        aggByName(request, "brandAgg","brand" , 10);

        aggByName(request,"categoryAgg" ,"category" ,10 );

        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            Map<String, List<String>> resultMap = new HashMap<>();

            List<String> brandList = getListByAggName(response, "brandAgg");
            resultMap.put("brand", brandList);

            List<String> categoryList = getListByAggName(response, "categoryAgg");
            resultMap.put("category", categoryList);

            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    private void queryCondition(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (params.getKey() != null && !"".equals(params.getKey())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", params.getKey()));
        }else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        if (params.getBrand() != null && !"".equals(params.getBrand())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand",params.getBrand()));
        }

        if (params.getCategory() != null && !"".equals(params.getCategory())){
            boolQueryBuilder.filter(QueryBuilders.termQuery("category",params.getCategory()));
        }

        if ((params.getMinPrice() != null && !"".equals(params.getMinPrice()))&&(params.getMaxPrice() != null && !"".equals(params.getMaxPrice()))){
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gt(params.getMinPrice()*100).lt(params.getMaxPrice()*100));
        }

        //做广告：为isAD是true的酒店增加分数
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        // 原始查询，相关性算分的查询
                        boolQueryBuilder,
                        // function score的数组
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                // 其中的一个function score 元素
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        // 过滤条件
                                        QueryBuilders.termQuery("isAD", true),
                                        // 算分函数
                                        ScoreFunctionBuilders.weightFactorFunction(100)
                                )
                        })
                        //算分方式，现在是求和
                        .boostMode(CombineFunction.SUM);
        //2.1.2 封装查询条件

        request.source().query(functionScoreQuery);
    }

    private void aggByName(SearchRequest request, String aggName, String fieldName, Integer size) {
        request.source()
                .size(0)
                .aggregation(
                        AggregationBuilders
                                .terms(aggName)
                                .field(fieldName)
                                .size(size)
                );
    }

    private List<String> getListByAggName(SearchResponse response, String aggName) {
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : brandAggBuckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }
}
